package com.demo.swingquickticket;

import com.alibaba.fastjson.JSONObject;
import com.demo.swingquickticket.service.DataService;
import com.demo.swingquickticket.service.GrabTicketService;
import com.demo.swingquickticket.swing.MainFrame;
import com.demo.swingquickticket.util.HttpClientUtil;
import com.demo.swingquickticket.util.HttpInfo;
import com.demo.swingquickticket.util.redis.CacheUtil;
import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootApplication
public class SwingQuickTicketApplication implements ApplicationListener {

    @Autowired
    CacheUtil cacheUtil;

    @Autowired
    GrabTicketService grabTicketService;

    public static void main(String[] args) {
        SpringApplicationBuilder builder = new SpringApplicationBuilder(SwingQuickTicketApplication.class);
        SpringApplication application = builder.headless(false).web(WebApplicationType.NONE).application();
        application.addListeners(new SwingQuickTicketApplication());
        application.run(args);
        new MainFrame();
    }

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        if (applicationEvent instanceof ApplicationReadyEvent) {
            if (cacheUtil != null) {
                System.out.println("项目启动，从redis读取用户数据");
                DataService.getAccount();
                grabTicketService.work();
            }
        } else if (applicationEvent instanceof ContextClosedEvent) {
            if (cacheUtil != null) {
                System.out.println("项目退出，保存用户数据到redis");
                DataService.saveAccount();
            }
        }
    }
}
